package com.slipper.system.controller;

import com.slipper.core.gson.GsonUtil;
import com.slipper.system.backup.service.BackupRestoreService;
import com.slipper.system.codeless.vo.DictionaryVO;
import com.slipper.system.dictionary.bo.DictionaryBO;
import com.slipper.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/system/dictionary")
public class CodelessDictionaryController {
    private static final Logger logger = LoggerFactory.getLogger(CodelessDictionaryController.class);

    @Resource
    private BackupRestoreService backupRestoreService;

    @PostMapping(value = "/exportData")
    public void exportData(HttpServletResponse response, @RequestBody DictionaryBO bo) {
        String fileName = "dictionary-" + DateUtil.format(new Date(), "dd-HH-mm-ss") + ".dat";
        DictionaryVO vo = backupRestoreService.backupDictionary(bo.getIds());
        FileUtil.downloadContent(response, fileName, AESUtil.encrypt(GsonUtil.toJson(vo)));
    }

    @PostMapping(value = "/importData")
    public String importData(DictionaryBO bo) {
        if (bo.getFile() == null) {
            return ResultUtil.failureResult("请选择上传文件！");
        }

        try {
            String content = new String(bo.getFile().getBytes(), StandardCharsets.UTF_8);
            backupRestoreService.restoreDictionary(AESUtil.decrypt(content));
            return ResultUtil.successResult("导入字典成功。");
        } catch (Exception e) {
            logger.error("文件解释出错！", e);
            return ResultUtil.failureResult("文件解释出错！");
        }
    }
}
